package jdbc.pool.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DbUtils_Druid {

    //1创建连接池对象
    private static DruidDataSource dataSource;

    static {

        //Properties 属性集合  (1)没有泛型   （2）存储字符串类型  （3）和流有关
        Properties properties=new Properties();
        //使用类加载器的方式获取流
        InputStream is = DbUtils.class.getClassLoader().getResourceAsStream("druid.properties");
        try {
            properties.load(is);
            //初始化连接池
            dataSource= (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("初始化连接池失败");
        }
    }


    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void closeAll(Connection conn, Statement stat, ResultSet rs){
        try {
            if(rs!=null){
                rs.close();
            }
            if(stat!=null){
                stat.close();
            }
            if(conn!=null){
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public static int executeUpdate(String sql,Object... params){
        //1获取连接
        Connection conn=null;
        PreparedStatement pstat=null;
        try {
            conn = getConnection();
            assert conn != null;
            pstat = conn.prepareStatement(sql);
            if(params!=null){
                for (int i = 0; i < params.length; i++) {
                    pstat.setObject(i+1, params[i]);
                }
            }
            return pstat.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            closeAll(conn, pstat, null);
        }

        return -1;

    }
}
